package com.superyee.commonlib.http;

import android.content.Context;

import com.superyee.commonlib.constants.StaticConstant;
import com.superyee.commonlib.utils.SpUtils;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class TokenAuthInterceptor implements Interceptor {

    private Context mContext;
    private Lock lock = new ReentrantLock();

    private TokenAuthInterceptor() {

    }

    public TokenAuthInterceptor(Context context) {
        this.mContext = context.getApplicationContext();
    }

//    boolean refreshToken() {
//        //间隔10天刷新一次token
//        long lastRefresh = SpUtils.getLong(mContext, StaticConstant.SP.REFRESH_TOKEN_TIME, 0);
//        return Math.abs(System.currentTimeMillis() - lastRefresh) > 3600000 * 24 * 10;
//    }

    @Override
    public Response intercept(Chain chain) throws IOException {
//        if (refreshToken()) {
//            try {
//                lock.lock();
//                getNewToken(chain);
//            } catch (Exception e) {
//                e.printStackTrace();
//                CrashReport.postCatchedException(new Throwable("TokenAuthInterceptor.getNewToken异常 " + e.getMessage()));
//            } finally {
//                lock.unlock();
//            }
//        }
        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);
        return response;
    }


    /**
     * //抢占同步锁
     * if (lock.tryLock()) {
     * //                AppLog.printD("TokenAuthInterceptor", "刷新 token  " + TimeUtil.getCurrentTime("HH:mm:ss SSS"));
     * try {
     * getNewToken(chain);
     * //                    AppLog.printD("TokenAuthInterceptor", "刷新token成功 " + TimeUtil.getCurrentTime("HH:mm:ss SSS"));
     * } catch (Exception e) {
     * e.printStackTrace();
     * CrashReport.postCatchedException(new Throwable("TokenAuthInterceptor.getNewToken异常 " + e.getMessage()));
     * //                    AppLog.printD("TokenAuthInterceptor", e.getMessage());
     * } finally {
     * lock.unlock();
     * }
     * } else {
     * //                AppLog.printD("TokenAuthInterceptor", "等待其他线程刷新token  " + TimeUtil.getCurrentTime("HH:mm:ss SSS"));
     * lock.lock();    //其他线程占用锁期间,保持等待
     * lock.unlock();
     * //                AppLog.printD("TokenAuthInterceptor", "其他线程刷新token成功  " + TimeUtil.getCurrentTime("HH:mm:ss SSS"));
     * }
     * //            AppLog.printD("TokenAuthInterceptor", "重新发起请求" + TimeUtil.getCurrentTime("HH:mm:ss SSS"));
     * String newToken = SpUtils.getString(mContext, StaticConstant.SP.ACCESS_TOKEN, "");
     * if (TextUtils.isEmpty(newToken)) {
     * AndroidUtil.showToast(mContext, "token 为空");
     * AppLog.printD("TokenAuthInterceptor", "token 为空");
     * }
     * if (isTokenExpired(response) && !TextUtils.isEmpty(newToken)) {
     * //使用新的Token，重新发起请求
     * Request newRequest = originalRequest
     * .newBuilder()
     * .removeHeader(StaticConstant.SP.AUTHORIZATION)
     * .removeHeader("Accept")
     * .addHeader("Accept", AppConfig.HEADER_ACCEPT)
     * .header(StaticConstant.SP.AUTHORIZATION, "Bearer " + newToken)
     * .build();
     * //            重新请求
     * return chain.proceed(newRequest);
     * }
     *
     * @param token
     * @return
     */
    /**
     private Request createTokenRequest(String token) {
     return new Request.Builder()
     .url(StaticConstant.UrlConstant.TOKEN_REFRESH)
     .addHeader("Accept", AppConfig.HEADER_ACCEPT)
     .addHeader(StaticConstant.SP.AUTHORIZATION, "Bearer " + token)
     .build();
     }

     private String getNewToken(Chain chain) {
     String accessToken = SpUtils.getString(mContext, StaticConstant.SP.ACCESS_TOKEN, "");
     if (TextUtils.isEmpty(accessToken)) {
     return "";
     }
     if (!refreshToken()) {
     return accessToken;
     }
     String responseResult = null;
     String result = null;
     Response response = null;
     int code = 0;
     try {
     Request tokenRequest = createTokenRequest(accessToken);
     response = chain.proceed(tokenRequest);
     code = response.code();
     responseResult = response.body().string();
     if (code != 200) {
     String msg = " TokenAuthInterceptor.getNewToken()=======  code = " + code + "  result = " + responseResult + " " + accessToken;
     AppLog.printD("TokenAuthInterceptor", msg);
     CrashReport.postCatchedException(new Throwable(msg));
     logout();
     return "";
     }
     JSONObject json = JSON.parseObject(responseResult);
     if (json != null) {
     String token = json.getString(StaticConstant.Response.TOKEN);
     if (!TextUtils.isEmpty(token)) {
     SpUtils.putString(mContext, StaticConstant.SP.ACCESS_TOKEN, token);
     SpUtils.putLong(mContext, StaticConstant.SP.REFRESH_TOKEN_TIME, System.currentTimeMillis());
     result = token;
     //                    AppLog.printD("TokenAuthInterceptor", token);
     }
     UserInfoBean userInfo = GsonHelper.fromJson(json.getString("user"), UserInfoBean.class);
     if (userInfo != null) {
     userInfo.setPasswordHasBeenSet(SpUtils.getUserInfo(mContext).passwordHasBeenSet());
     SpUtils.setCurrentUser(mContext, userInfo);
     SpUtils.putString(mContext, StaticConstant.SP.NET_EASE_TOKEN, userInfo.getImToken());
     SpUtils.putString(mContext, StaticConstant.SP.ACCID, userInfo.getId());
     }
     } else {
     String msg = " TokenAuthInterceptor.getNewToken()=======  code  " + code + "  result = " + responseResult;
     AppLog.printD("TokenAuthInterceptor", msg);
     CrashReport.postCatchedException(new Throwable(msg));
     logout();
     }
     } catch (Exception e) { //包含请求超时等异常
     e.printStackTrace();
     String msg = " TokenAuthInterceptor.getNewToken()======= 捕获异常 " + e.getMessage() + "  code = " + code + "  result = " + responseResult;
     AppLog.printD("TokenAuthInterceptor", msg);
     CrashReport.postCatchedException(new Throwable(msg));
     //            logout();
     } finally {
     try {
     if (response != null) {
     response.body().close();
     }
     } catch (Exception e) {
     }
     }
     return result;
     }

     private void logout() {
     AppLog.printD("TokenAuthInterceptor", "token异常退出登录");
     ObserverManager.getInstence().notifyUi(BaseActions.LOGIN_OUT, null, ObserverManager.SUCCESS);
     }
     **/

}
